/*	BuildBunker class definition.
 *
*/

#include "BuildingPlacer.h"
#include "BuildBunker.h"

void BuildBunker::Enter()
{
	DEBUG_PRINT("BuildBunker(%p) %s entering\n", this, GetName().c_str());

}

void BuildBunker::Execute()
{
	DEBUG_PRINT("BuildBunker(%p) %s executing\n", this, GetName().c_str());
	Base* base = BB->GetBases()->front();
	std::list<BWAPI::Unit*>* scvs = (base)->GetUnitsByType(BWAPI::UnitTypes::Terran_SCV);
	std::list<BWAPI::Unit*>::iterator it = scvs->begin();
		
	if (!builder)
	{
		for (; it!=scvs->end(); it++)
		{
			if (((*it)->isGatheringMinerals() || (*it)->isIdle()) && !(*it)->isCarryingMinerals()) break;
		}
		builder = (*it);
	}
	
	BWAPI::TilePosition pos = BuildPlacer->getBuildLocationNear(base->GetBaseLocation(),BWAPI::UnitTypes::Terran_Armory);
	DEBUG_PRINT("BuildBunker(%p) attempting to build engineering bay at tile position(%d,%d).\n", this, pos.x(),pos.y());
	
	builder->build(pos,BWAPI::UnitTypes::Terran_Armory);
	builder =  NULL;
	BB->ResetOrder();
	control->FinishWithSuccess();
}

void BuildBunker::Exit()
{
	DEBUG_PRINT("BuildBunker(%p) %s exiting\n", this, GetName().c_str());
	
}

bool BuildBunker::CheckConditions()
{
	DEBUG_PRINT("BuildBunker(%p) %s checking conditions\n", this, GetName().c_str());
	
	std::list<BWAPI::Unit*>* marines = BB->GetUnitsByTypeGeneral(BWAPI::UnitTypes::Terran_Marine);
	if( marines)
	{
		if(marines->size() > 4)
		{
			
			if(BB->isBuildBuilding(BWAPI::UnitTypes::Terran_Armory) )
			{
				DEBUG_PRINT("BuildBunker(%p) %s checked conditions and has %d minerals to spend\n", this, GetName().c_str(), BB->GetMineralsToSpend());
				BB->SpendResources(BWAPI::UnitTypes::Terran_Armory);
				return true;
			}
		}
		
		else
		{
			if(BB->isBuildBuilding(BWAPI::UnitTypes::Terran_Armory) )
			{
				DEBUG_PRINT("BuildBunker(%p) %s checked conditions and has %d minerals to spend\n", this, GetName().c_str(), BB->GetMineralsToSpend());
				BB->SpendResources(BWAPI::UnitTypes::Terran_Armory);
				return true;
			}
		}
	}

	return false;
}